package com.sunny.openplatformutils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunny.openplatformutils.utils.HttpUtil;


/**
 * 
 * @author Sunny
 *
 */
public class Weixin {

	private static String WEB_APPID, WEB_SECRET;
	private static final String userInfoURL = "https://api.weixin.qq.com/sns/userinfo";
	private static final String accessTokenURL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	
	private static Logger logger = LoggerFactory.getLogger(Weixin.class);

	public static void init(String webAppid, String webSecret, String mobileAppid, String mobileAppKey) {
		WEB_APPID = webAppid;
		WEB_SECRET = webSecret;
	}
	
	/**
	 * 获取微信AccessToken
	 * @return
	 */
	public static String getAccessToken(String code) {
		try {
			StringBuilder url = new StringBuilder(accessTokenURL)
				.append("?appid=").append(WEB_APPID)
				.append("&secret=").append(WEB_SECRET)
				.append("&code=").append(code)
				.append("&grant_type=authorization_code");
		return HttpUtil.get(url.toString());
		} catch (Exception e) {
			logger.error(e.getMessage() + ":" + e.getStackTrace());
			return "";
		}
	}
	
	public static String getUserInfo(String accessToken, String openId) {
		try {
			StringBuilder url = new StringBuilder(userInfoURL)
					.append("?access_token=").append(accessToken)
					.append("&openid=").append(openId);
			return HttpUtil.get(url.toString());
		} catch (Exception e) {
			logger.error(e.getMessage() + ":" + e.getStackTrace());
			return "";
		}
	}
}
